package cn.edu.cdu.argorithm.impl;

import cn.edu.cdu.argorithm.IClimbStairs;

public class ClimbStairsSolutions {
    public static class Solution1 implements IClimbStairs {
        @Override
        public int climbStairs(int n) {
            if(n == 1 || n == 2)
                return n;
            return climbStairs(n - 1) + climbStairs(n - 2);
        }
    }

    public static class Solution2 implements IClimbStairs {
        @Override
        public int climbStairs(int n) {
            int p = 0, q = 0, r = 1;
            for (int i = 0; i < n; i++) {
                p = q;
                q = r;
                r = p + q;
            }
            return r;
        }
    }

    public static class Solution3 implements IClimbStairs {

        @Override
        public int climbStairs(int n) {
            int[][] q = {{1, 1}, {1, 0}};
            int[][]res = pow(q, n);
            return res[0][0];
        }

        public int[][] pow(int[][] a, int n) {
            int[][] ret = {{1, 0}, {0, 1}};
            while(n > 0) {
                if((n & 1) == 1) {
                    ret = multiply(a, ret);
                }
                n >>= 1;
                a = multiply(a, a);
            }
            return ret;
        }

        public int[][] multiply(int[][] a, int[][] b) {
            int[][] c = new int[2][2];
            for (int i = 0; i < 2; i++) {
                for (int j = 0; j < 2; j++) {
                    c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j];
                }
            }
            return c;
        }
    }

    public static class Solution4 implements IClimbStairs{
        @Override
        public int climbStairs(int n) {
            double sqrt5 = Math.sqrt(5);
            double fibn = Math.pow((1 + sqrt5) / 2, n + 1) - Math.pow((1 - sqrt5) / 2, n + 1);
            return (int)Math.round(fibn / sqrt5);
        }
    }
}
